package com.exam.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.exam.common.vo.ExamStuVO;
import com.exam.common.vo.ExamTeacherVO;

public class LoginInterceptor extends HandlerInterceptorAdapter {

	private final static String[] IGNORE_URL = {"/home","/login"};
	private final static String[] IGNORE_STU_URL = {"/subject","/exam"};
	private final static String[] UN_IGNORE_STU = {"/tea","/stu"};
	private final static String[] IGNORE_TEA_URL = {"/stu","/ti","/subject","/grade"};
	private final static String[] UN_IGNORE_TEA = {"/tea"};
	
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		super.postHandle(request, response, handler, modelAndView);
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		boolean isClient = false;
		String currentUrl = request.getRequestURL().toString(); 
		
		//排除不需要拦截的url
		for(String url : IGNORE_URL){
			if(currentUrl.contains(url)){
				isClient = true;
				break;
			}
		}
		
		
		if(!isClient){
			ExamTeacherVO teacher = (ExamTeacherVO) request.getSession().getAttribute("teacher");
			ExamStuVO stuVO = (ExamStuVO) request.getSession().getAttribute("stuVO");
			String client = "";
			//显示登录用户名
			if(teacher!=null){
				client = teacher.getExamTeacherName();
			}else if(stuVO!=null){
				client = stuVO.getExamStuName();
			}
			//
			request.getSession().setAttribute("client", client);
			
			if(stuVO!=null){
				for(String stuUrl:IGNORE_STU_URL){
					if(currentUrl.contains(stuUrl)){
						isClient = true;
						break;
					}
				}
				for(String unStuUrl:UN_IGNORE_STU){
					if(currentUrl.contains(unStuUrl)){
						isClient = false;
						break;
					}
				}
				if(!isClient){
					response.sendRedirect(request.getContextPath()+"/subject/subjectList");
				}
			}
			System.out.println(isClient);
			if(teacher !=null){
				for(String teaUrl:IGNORE_TEA_URL){
					if(currentUrl.contains(teaUrl)){
						isClient = true;
						break;
					}
				}
				for(String unTeaUrl:UN_IGNORE_TEA){
					if(currentUrl.contains(unTeaUrl)){
						isClient = false;
						break;
					}
				}
				if(!isClient){
					response.sendRedirect(request.getContextPath()+"/stu/stuList");
				}
			}
			if(teacher != null || stuVO != null){
				isClient = true;
			}else{
				response.sendRedirect(request.getContextPath()+"/home");
			}
		}
		return isClient;
	}
	
}
